﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using Aspose.Cells;
using ePlanet.Entities;
using System.Collections.Specialized;
using System.Configuration;

namespace FilesUpload
{
    public partial class Form1 : Form
    {
        private string userId = string.Empty;

        private string catalogId = string.Empty;

        private string webAddress = string.Empty;

        private string type = string.Empty;

        List<EntityIdAndTypeRelateAttachFilePath> OrignalFilesUploadDatas = null;

        List<EntityIdAndTypeRelateAttachFilePath> FilesUploadDatas = null;

        private string templateFilePath = string.Empty;

        private string templateFileDirectoryPath = string.Empty;

        private CodeTable codeTable = null;

        public string ArchiveCatalogId
        {
            get
            {
                string type = string.Empty;
                string selectedText = string.Concat(this.cboSelectTemplate.SelectedItem);
                if (selectedText == "请选择...")
                {
                    throw new Exception("请先选择模板分类！");
                }
                else if (selectedText == "文书")
                {
                    type = "1";
                }
                else if (selectedText == "光盘")
                {
                    type = "2";
                }
                else if (selectedText == "科研")
                {
                    type = "3";
                }
                else if (selectedText == "基建")
                {
                    type = "4";
                }
                else if (selectedText == "设备")
                {
                    type = "5";
                }
                else if (selectedText == "会计凭证")
                {
                    type = "61";
                }
                else if (selectedText == "会计账簿")
                {
                    type = "62";
                }
                else if (selectedText == "财务报告")
                {
                    type = "63";
                }
                else if (selectedText == "会计其他")
                {
                    type = "64";
                }
                else if (selectedText == "勘探综合")
                {
                    type = "71";
                }
                else if (selectedText == "勘探单井")
                {
                    type = "72";
                }
                else if (selectedText == "声像视频")
                {
                    type = "81";
                }
                else if (selectedText == "声像音频")
                {
                    type = "82";
                }
                else if (selectedText == "声像图像")
                {
                    type = "83";
                }
                else if (selectedText == "荣誉")
                {
                    type = "91";
                }
                else if (selectedText == "文书卷")
                {
                    type = "101";
                }
                else if (selectedText == "文书卷内件")
                {
                    type = "102";
                }
                else if (selectedText == "综合卷")
                {
                    type = "7101";
                }
                else if (selectedText == "综合卷内件")
                {
                    type = "7102";
                }
                else
                {
                    throw new Exception("请先选择模板分类！");
                }
                this.catalogId = type;
                return this.catalogId;
            }
            set
            {
                switch (value)
                {
                    case "1":
                        this.cboSelectTemplate.SelectedItem = "文书";
                        break;
                    case "2":
                        this.cboSelectTemplate.SelectedItem = "光盘";
                        break;
                    case "3":
                        this.cboSelectTemplate.SelectedItem = "科研";
                        break;
                    case "4":
                        this.cboSelectTemplate.SelectedItem = "基建";
                        break;
                    case "5":
                        this.cboSelectTemplate.SelectedItem = "设备";
                        break;
                    case "61":
                        this.cboSelectTemplate.SelectedItem = "会计凭证";
                        break;
                    case "62":
                        this.cboSelectTemplate.SelectedItem = "会计账簿";
                        break;
                    case "63":
                        this.cboSelectTemplate.SelectedItem = "财务报告";
                        break;
                    case "64":
                        this.cboSelectTemplate.SelectedItem = "会计其他";
                        break;
                    case "71":
                        this.cboSelectTemplate.SelectedItem = "勘探综合";
                        break;
                    case "72":
                        this.cboSelectTemplate.SelectedItem = "勘探单井";
                        break;
                    case "81":
                        this.cboSelectTemplate.SelectedItem = "声像视频";
                        break;
                    case "82":
                        this.cboSelectTemplate.SelectedItem = "声像音频";
                        break;
                    case "83":
                        this.cboSelectTemplate.SelectedItem = "声像图像";
                        break;
                    case "91":
                        this.cboSelectTemplate.SelectedItem = "荣誉";
                        break;
                    case "101":
                        this.cboSelectTemplate.SelectedItem = "文书卷";
                        break;
                    case "102":
                        this.cboSelectTemplate.SelectedItem = "文书卷内件";
                        break;
                    case "7101":
                        this.cboSelectTemplate.SelectedItem = "综合卷";
                        break;
                    case "7102":
                        this.cboSelectTemplate.SelectedItem = "综合卷内件";
                        break;
                    default:
                        throw new Exception("Type Error!");
                }
                this.catalogId = value;
            }
        }

        public string CatalogId
        {
            get
            {
                if (type == "SingleWell")
                {
                    return this.catalogId;
                }
                else
                {
                    return this.ArchiveCatalogId;
                }
            }
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                NameValueCollection nameValueTable = helper.GetQueryStringParameters();
                userId = nameValueTable.Get("UserId");
                catalogId = nameValueTable.Get("CatalogId");
                webAddress = nameValueTable.Get("WebAddress");
                type = nameValueTable.Get("Type");

                type = "SingleWell";
                type = "Archive";
                userId = "cc7a57e6-28bd-42ed-a75c-0379528062ec";
                catalogId = "72";
                webAddress = "http://localhost:6180/EOAU";

                if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(webAddress) || string.IsNullOrEmpty(type) || string.IsNullOrEmpty(catalogId))
                {
                    MessageBox.Show("程序打开时发生错误，请重新打开！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                }

                string dataIds = nameValueTable.Get("DataIds");
                //dataIds = "%5B%7B%22EntityId%22:%227819c922-6faa-42a7-8c7f-de03155ae4e0%22,%22Type%22:null,%22AttachFilePath%22:null,%22ArchiveNum%22:%22DQYT.218.11-W-0000012%22%7D,%7B%22EntityId%22:%228e294051-009e-4dcf-808c-e9cc451c92be%22,%22Type%22:null,%22AttachFilePath%22:null,%22ArchiveNum%22:%22DQYT.218-W-0000014%22%7D%5D";
                if (!string.IsNullOrEmpty(dataIds))
                {
                    string jsonStr = Uri.UnescapeDataString(dataIds);
                    this.OrignalFilesUploadDatas = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EntityIdAndTypeRelateAttachFilePath>>(jsonStr);
                    if (this.OrignalFilesUploadDatas == null || this.OrignalFilesUploadDatas.Count == 0)
                    {
                        MessageBox.Show("程序打开时发生错误，请重新打开！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.Close();
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine("将为下列档号追加电子文件, 请选择正确的文件夹进行电子文件的导入:");
                        foreach (EntityIdAndTypeRelateAttachFilePath item in this.OrignalFilesUploadDatas)
                        {
                            sb.AppendLine(item.ArchiveNum);
                        }
                        MessageBox.Show(sb.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                string getCodeTableAddress = helper.GetGetCodeTableHandlerPath();
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(getCodeTableAddress));
                WebResponse webRespon = httpReq.GetResponse();
                Stream s = webRespon.GetResponseStream();
                StreamReader sr = new StreamReader(s);
                string str = sr.ReadToEnd();
                codeTable = Newtonsoft.Json.JsonConvert.DeserializeObject<CodeTable>(str);
                s.Close();
                sr.Close();
                this.SetFormControlState();
            }
            catch (Exception ex)
            {
                MessageBox.Show("程序打开时发生错误，" + ex.Message + "请重新打开！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        private void SetFormControlState()
        {
            if (!string.IsNullOrEmpty(this.type))
            {
                if (type != "SingleWell")
                {
                    if (!string.IsNullOrEmpty(catalogId))
                    {
                        this.ArchiveCatalogId = catalogId;
                    }
                    else
                    {
                        //this.cboSelectTemplate.SelectedItem = "请选择...";
                    }
                    if (this.OrignalFilesUploadDatas == null)
                    {
                        this.panel2.Visible = true;
                        this.lblSelectDirectory.Visible = false;
                        this.txtSelectDirectory.Visible = false;
                        this.btnSelectDirectory.Visible = false;
                        this.lblSelectTemplate.Visible = true;
                        this.cboSelectTemplate.Visible = true;
                        this.llblGetTemplate.Visible = true;
                        this.cboSelectTemplate.Enabled = false;
                        this.lblSelectFile.Text = "选择文件：";
                    }
                    else
                    {
                        this.lblSelectDirectory.Visible = false;
                        this.txtSelectDirectory.Visible = false;
                        this.btnSelectDirectory.Visible = false;
                        this.btnOpenDirectory.Visible = false;
                        this.lblSelectTemplate.Visible = true;
                        this.cboSelectTemplate.Visible = true;
                        this.cboSelectTemplate.Enabled = false;
                        this.lblSelectFile.Text = "选择目录：";
                    }
                }
            }
            else
            {
                this.panel2.Visible = true;
                this.lblSelectDirectory.Visible = true;
                this.txtSelectDirectory.Visible = true;
                this.btnSelectDirectory.Visible = true;
                this.lblSelectTemplate.Visible = false;
                this.cboSelectTemplate.Visible = false;
                this.llblGetTemplate.Visible = false;
                this.lblSelectFile.Text = "选择文件";
            }
        }

        private void llblGetTemplate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                string templateFileAddress = helper.GetUploadTemplatePath(type, CatalogId);
                string uploadTemplateName = helper.GetTemplateName(templateFileAddress);
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(templateFileAddress));
                WebResponse webRespon = httpReq.GetResponse();
                Stream s = webRespon.GetResponseStream();
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.DefaultExt = "xls";
                saveFileDialog.FileName = uploadTemplateName;
                saveFileDialog.Filter = "Excel (*.xls)|*.xls";
                saveFileDialog.Title = "保存批量上传模板";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string tempTemplateFilePath = saveFileDialog.FileName;
                    FileStream fileStream = new FileStream(tempTemplateFilePath, FileMode.Create);
                    int bufferLength = 4096;
                    byte[] buffer = new byte[bufferLength];
                    int size = 0;
                    while ((size = s.Read(buffer, 0, bufferLength)) > 0)
                    {
                        fileStream.Write(buffer, 0, size);
                    }
                    fileStream.Flush();
                    fileStream.Close();

                    this.btnOpenDirectory.Enabled = true;
                    templateFilePath = tempTemplateFilePath;
                    templateFileDirectoryPath = Path.GetDirectoryName(tempTemplateFilePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void btnSelectDirectory_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                folderBrowserDialog.ShowNewFolderButton = false;
                folderBrowserDialog.Description = "请选择批量上传目录";
                if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (!Directory.Exists(folderBrowserDialog.SelectedPath))
                    {
                        MessageBox.Show("你选择的路径不存在，请重新选择！");
                        return;
                    }
                    this.txtSelectDirectory.Text = folderBrowserDialog.SelectedPath;
                    string templateFileAddress = helper.GetUploadTemplatePath(type, CatalogId);
                    string uploadTemplateName = helper.GetTemplateName(templateFileAddress);
                    HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(templateFileAddress));
                    WebResponse webRespon = httpReq.GetResponse();
                    Stream s = webRespon.GetResponseStream();
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.DefaultExt = "xls";
                    saveFileDialog.FileName = uploadTemplateName;
                    saveFileDialog.Filter = "Excel (*.xls)|*.xls";
                    saveFileDialog.Title = "保存批量上传模板";
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        string tempTemplateFilePath = saveFileDialog.FileName;
                        FileStream fileStream = new FileStream(tempTemplateFilePath, FileMode.Create);
                        int bufferLength = 4096;
                        byte[] buffer = new byte[bufferLength];
                        int size = 0;
                        while ((size = s.Read(buffer, 0, bufferLength)) > 0)
                        {
                            fileStream.Write(buffer, 0, size);
                        }
                        fileStream.Flush();
                        fileStream.Close();

                        this.btnOpenDirectory.Enabled = true;
                        templateFilePath = tempTemplateFilePath;
                        templateFileDirectoryPath = Path.GetDirectoryName(tempTemplateFilePath);

                        //自动附加当前文件夹中的pdf文档。

                        Workbook workbook = new Workbook();
                        workbook.Open(tempTemplateFilePath);
                        Cells cells = workbook.Worksheets[0].Cells;
                        Cell cell = null;

                        int rowIndex = 1;
                        string[] directories = Directory.GetDirectories(this.txtSelectDirectory.Text.Trim());
                        foreach (string directoryPath in directories)
                        {
                            DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
                            if (directoryInfo != null && directoryInfo.Exists)
                            {
                                FileInfo[] fileInfos = directoryInfo.GetFiles();
                                foreach (FileInfo fileInfo in fileInfos)
                                {
                                    if (fileInfo != null && fileInfo.Exists && fileInfo.Extension.ToLower() == ".pdf")
                                    {
                                        cell = cells[rowIndex, 0];
                                        cell.PutValue(rowIndex);
                                        cell = cells[rowIndex, 10];
                                        cell.PutValue(directoryInfo.Name);
                                        cell = cells[rowIndex, 2];
                                        cell.PutValue(fileInfo.FullName);
                                        rowIndex++;
                                    }
                                }
                            }
                        }
                        workbook.Save(tempTemplateFilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            if (this.OrignalFilesUploadDatas == null)
            {
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.Filter = "Excel (*.xls)|*.xls";
                fileDialog.FilterIndex = 1;
                fileDialog.Multiselect = false;
                fileDialog.CheckFileExists = true;
                fileDialog.CheckPathExists = true;
                fileDialog.InitialDirectory = templateFileDirectoryPath;
                fileDialog.FileName = templateFilePath;
                if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    this.txtSelectFile.Text = fileDialog.FileName;
                }
                if (!string.IsNullOrEmpty(this.txtSelectFile.Text.Trim()))
                {
                    this.btnUpload.Enabled = true;
                }
            }
            else
            {
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                folderBrowserDialog.ShowNewFolderButton = false;
                folderBrowserDialog.Description = "请选择批量上传目录";
                if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (!Directory.Exists(folderBrowserDialog.SelectedPath))
                    {
                        MessageBox.Show("你选择的路径不存在，请重新选择！");
                        return;
                    }
                    this.txtSelectFile.Text = folderBrowserDialog.SelectedPath;
                    string[] directories = Directory.GetDirectories(this.txtSelectFile.Text.Trim());
                    List<EntityIdAndTypeRelateAttachFilePath> fileEntities = new List<EntityIdAndTypeRelateAttachFilePath>();
                    foreach (string direct in directories)
                    {
                        foreach (EntityIdAndTypeRelateAttachFilePath item in this.OrignalFilesUploadDatas)
                        {
                            if (item != null && item.ArchiveNum == Path.GetFileName(direct))
                            {
                                string[] files = Directory.GetFiles(direct);
                                foreach (string file in files)
                                {
                                    fileEntities.Add(new EntityIdAndTypeRelateAttachFilePath(item.EntityId, file, string.Empty, item.ArchiveNum));
                                }
                                continue;
                            }
                        }
                    }
                    this.FilesUploadDatas = fileEntities;
                    if (this.FilesUploadDatas.Count == 0)
                    {
                        MessageBox.Show("待上传的文件列表为空请检查选择的文件夹是否有误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        Form2 form2 = new Form2();
                        form2.Entities = this.FilesUploadDatas;
                        form2.ShowDialog();
                        this.btnUpload.Enabled = true;
                    }
                }
            }
        }

        [Obsolete("过期的上传事件实现")]
        private void btnUpload_ClickBak(object sender, EventArgs e)
        {
            string type = string.Empty;
            string selectedText = string.Concat(this.cboSelectTemplate.SelectedText.Trim());
            if (selectedText == "请选择...")
            {
                MessageBox.Show("请先选择模板分类！");
                return;
            }
            else if (selectedText == "单井数据")
            {
                type = "1";
            }
            else if (selectedText == "文书类")
            {
                type = "2";
            }
            else if (selectedText == "产品类")
            {
                type = "3";
            }
            else if (selectedText == "科学技术研究类")
            {
                type = "4";
            }
            else if (selectedText == "建设项目类")
            {
                type = "5";
            }
            else if (selectedText == "设备仪器类")
            {
                type = "6";
            }
            else if (selectedText == "会计类")
            {
                type = "7";
            }
            else if (selectedText == "油气勘探开发类")
            {
                type = "8";
            }
            else if (selectedText == "声像类")
            {
                type = "9";
            }
            else if (selectedText == "实物类")
            {
                type = "10";
            }
            else if (selectedText == "文书卷")
            {
                type = "101";
            }
            else if (selectedText == "文书卷内件")
            {
                type = "102";
            }
            else if (selectedText == "综合卷")
            {
                type = "7101";
            }
            else if (selectedText == "综合卷内件")
            {
                type = "7102";
            }

            string templateProcessAddress = @"http://localhost:6180/EOAU/Views/DataManage/PLuploads/TemplateFileHandler.ashx" + "?fileType=" + type;
            string templateFilePath = this.txtSelectFile.Text.Trim();
            if (File.Exists(templateFilePath))
            {
                string saveName = Path.GetFileName(templateFilePath);
                string responseText = "";
                int returnValue = Upload_Request(templateProcessAddress, templateFilePath, saveName, this.progressBarUpload, out responseText);
                if (returnValue == 1)
                {

                }
                else
                {

                }
            }
            else
            {
                MessageBox.Show("选择的文件路径不存在！请重新选择！");
            }

            string fileUploadAddress = @"http://localhost:6180/EOAU/Views/DataManage/PLuploads/FileUploadHandler.ashx" + "?fileType=" + type + "&pid=";
            string fileNamePath = this.txtSelectFile.Text.Trim();
            if (File.Exists(fileNamePath))
            {
                string saveName = Path.GetFileName(fileNamePath);
                string responseText = "";
                int returnValue = Upload_Request(fileUploadAddress, fileNamePath, saveName, this.progressBarUpload, out responseText);
                if (returnValue == 1)
                {

                }
                else
                {

                }
            }
            else
            {
                MessageBox.Show("选择的文件路径不存在！请重新选择！");
            }
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpload_Click(object sender, EventArgs e)
        {
            this.btnUpload.Enabled = false;
            this.listLogMsg.Items.Clear();
            this.progressBarUpload.Value = 0;
            this.lblCurrentUploadFileName.Text = "";
            this.lblTime.Text = "";
            this.lblState.Text = "";
            this.lblSize.Text = "";
            this.lblSpeed.Text = "";

            int fileUploadCount = 0;

            if (this.FilesUploadDatas != null)
            {
                if (this.FilesUploadDatas.Count == 0)
                {
                    MessageBox.Show("待上传的文件列表为空请检查选择的文件夹是否有误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    try
                    {
                        UploadFiles(ref fileUploadCount, this.FilesUploadDatas);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        string msg = "";
                        if (fileUploadCount == this.FilesUploadDatas.Count)
                        {
                            msg += "全部文件上传成功！\r\n";
                        }
                        else
                        {
                            msg += "部分文件上传失败，请手动上传！\r\n";
                        }
                        MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    return;
                }
            }

            bool isTemplateUploadSuccess = false;
            ExcelFileProcess excelFileProcess = new ExcelFileProcess();
            List<EntityIdAndTypeRelateAttachFilePath> entityIdRelateAttachFilePathDict = new List<EntityIdAndTypeRelateAttachFilePath>();
            List<SingleWellEntity> singleWells = new List<SingleWellEntity>();
            UpdateArchiveAndPageFileModel<CommonEntityDTO, CommonEntityDTO> archiveAndPageFileModel = new UpdateArchiveAndPageFileModel<CommonEntityDTO, CommonEntityDTO>();
            string jsonStr = string.Empty;
            bool isTemplateError = false;
            try
            {
                if (type == "SingleWell")
                {
                    isTemplateError = excelFileProcess.SingleWellProcess(this.txtSelectFile.Text.Trim(), out singleWells, out entityIdRelateAttachFilePathDict, this.codeTable);
                }
                else
                {
                    isTemplateError = excelFileProcess.ReadExcel(this.txtSelectFile.Text.Trim(), codeTable, CatalogId, out archiveAndPageFileModel, out entityIdRelateAttachFilePathDict, this.txtSelectFile.Text.Trim());
                }
                if (isTemplateError)
                {
                    MessageBox.Show("模板填写错误，请修改后重试！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (entityIdRelateAttachFilePathDict.Count > 2000)
                {
                    MessageBox.Show("待上传的文件数目过大，请分开上传！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                bool flag = false;
                if (type == "SingleWell")
                {
                    if (!isTemplateError && singleWells.Count > 0)
                    {
                        jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(singleWells);
                        flag = true;
                    }
                }
                else
                {
                    if (!isTemplateError && (archiveAndPageFileModel.Archives.Count > 0 || archiveAndPageFileModel.PageFiles.Count > 0))
                    {
                        List<ArchiveNumQueryEntity> entitiesWithArchiveNum = new List<ArchiveNumQueryEntity>();
                        foreach (CommonEntityDTO item in archiveAndPageFileModel.Archives)
                        {
                            if (!string.IsNullOrEmpty(item.ArchiveNum))
                            {
                                ArchiveNumQueryEntity entity = new ArchiveNumQueryEntity();
                                entity.EntityId = item.DataId;
                                entity.ArchiveNum = item.ArchiveNum;
                                entitiesWithArchiveNum.Add(entity);
                            }
                        }
                        if (entitiesWithArchiveNum.Count > 0)
                        {
                            string queryStr = Newtonsoft.Json.JsonConvert.SerializeObject(entitiesWithArchiveNum);
                            string archiveNumRepeatQueryHandlerAddress = helper.GetArchiveNumRepeatQueryHandlerPath() + "?CatalogId=" + this.CatalogId;
                            NameValueCollection varPost = new NameValueCollection();
                            varPost.Add("data", queryStr);
                            WebClient webClient = new WebClient();
                            byte[] respons = webClient.UploadValues(archiveNumRepeatQueryHandlerAddress, "POST", varPost);
                            string responsStr = System.Text.Encoding.UTF8.GetString(respons);
                            //responsStr="[{\"EntityId\":\"9d04a76f-847d-4e32-b48c-20c5ab2ccbc8\",\"DataBaseEntityId\":\"7819c922-6faa-42a7-8c7f-de03155ae4e0\",\"ArchiveNum\":\"DQYT.218.11-W-0000012\",\"Title\":\"文书类新流程林志红测试xx\"}]";
                            if (!string.IsNullOrEmpty(responsStr) && !responsStr.StartsWith("Error"))
                            {
                                List<ArchiveNumQueryEntity> entities = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ArchiveNumQueryEntity>>(responsStr);
                                if (entities != null && entities.Count > 0)
                                {
                                    IList<BindingItem> items = new List<BindingItem>();
                                    foreach (ArchiveNumQueryEntity entity in entities)
                                    {
                                        BindingItem item = new BindingItem();
                                        item.DataId = entity.EntityId;
                                        item.DataBaseId = entity.DataBaseEntityId;
                                        item.ArchiveNum = entity.ArchiveNum;
                                        item.Title = entity.Title;
                                        item.IsSelect = false;
                                        items.Add(item);
                                    }
                                    SelectUploadArchive SelectUploadArchiveForm = new SelectUploadArchive();
                                    SelectUploadArchiveForm.Entities = items;
                                    System.Windows.Forms.DialogResult result = SelectUploadArchiveForm.ShowDialog(this);
                                    if (result == System.Windows.Forms.DialogResult.OK)
                                    {
                                        items = SelectUploadArchiveForm.Entities;
                                        List<CommonEntityDTO> ArchiveEntities = new List<CommonEntityDTO>();
                                        List<CommonEntityDTO> pageEntities = new List<CommonEntityDTO>();
                                        foreach (CommonEntityDTO entity in archiveAndPageFileModel.Archives)
                                        {
                                            bool isSelect = true;
                                            string tempId = entity.DataId;
                                            foreach (BindingItem item in items)
                                            {
                                                if (item.ArchiveNum == entity.ArchiveNum && item.DataId == entity.DataId)
                                                {
                                                    if (item.IsSelect)
                                                    {
                                                        entity.DataRowOpMode = "Update";
                                                        entity.DataId = item.DataBaseId;
                                                    }
                                                    else
                                                    {
                                                        isSelect = false;
                                                    }
                                                    break;
                                                }
                                            }
                                            if (isSelect)
                                            {
                                                ArchiveEntities.Add(entity);
                                                foreach (EntityIdAndTypeRelateAttachFilePath file in entityIdRelateAttachFilePathDict)
                                                {
                                                    if (file.EntityId == tempId)
                                                    {
                                                        file.EntityId = entity.DataId;
                                                    }
                                                }
                                                foreach (CommonEntityDTO page in archiveAndPageFileModel.PageFiles)
                                                {
                                                    if (page.F_ArchiveId == tempId)
                                                    {
                                                        page.F_ArchiveId = entity.DataId;
                                                        pageEntities.Add(page);
                                                    }
                                                }
                                            }
                                        }
                                        archiveAndPageFileModel.Archives = ArchiveEntities;
                                        archiveAndPageFileModel.PageFiles = pageEntities;
                                    }
                                    else
                                    {
                                        MessageBox.Show("待上传著录项信息信息为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show("服务器发生错误：" + responsStr, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        if (archiveAndPageFileModel.Archives.Count > 0 || archiveAndPageFileModel.PageFiles.Count > 0)
                        {
                            jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(archiveAndPageFileModel);
                            flag = true;
                        }
                    }
                }

                if (flag)
                {
                    string templateFileHandlerAddress = helper.GetTemplateFileHandlerPath() + "?UserId=" + this.userId + "&CatalogId=" + this.CatalogId + "&Type=" + this.type;
                    NameValueCollection varPost = new NameValueCollection();
                    varPost.Add("data", jsonStr);
                    WebClient webClient = new WebClient();
                    byte[] respons = webClient.UploadValues(templateFileHandlerAddress, "POST", varPost);
                    string responsStr = System.Text.Encoding.UTF8.GetString(respons);
                    if (responsStr.StartsWith("Success"))
                    {
                        isTemplateUploadSuccess = true;
                        this.listLogMsg.Items.Add("著录项信息上传成功！");
                        Application.DoEvents();

                        UploadFiles(ref fileUploadCount, entityIdRelateAttachFilePathDict);
                    }
                    else
                    {
                        MessageBox.Show("著录项信息上传失败！" + responsStr, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("待上传著录项信息信息为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                string msg = "";
                if (isTemplateUploadSuccess)
                {
                    this.btnUpload.Enabled = false;
                    msg += "著录项信息上传成功！\r\n";
                }
                else
                {
                    msg += "著录项信息上传失败！\r\n";
                }
                if (fileUploadCount != entityIdRelateAttachFilePathDict.Count)
                {
                    this.btnExportErrorToExcel.Enabled = true;
                    msg += "部分文件上传失败，请手动上传！\r\n";
                }
                else if (fileUploadCount > 0)
                {
                    this.btnExportErrorToExcel.Enabled = false;
                    msg += "全部文件上传成功！\r\n";
                }
                msg += "具体信息请查看日志消息！";
                MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        private void UploadFiles(ref int fileUploadCount, List<EntityIdAndTypeRelateAttachFilePath> entityIdRelateAttachFilePathDict)
        {
            foreach (EntityIdAndTypeRelateAttachFilePath kvp in entityIdRelateAttachFilePathDict)
            {
                string fileUploadAddress = helper.GetFileUploadHandlerPath() + "?EntityId=" + kvp.EntityId + "&UserId=" + this.userId + "&Type=" + this.type + "&CatalogId=" + this.CatalogId + "&Flag=" + kvp.Type;
                string fileNamePath = kvp.AttachFilePath;
                string saveName = Path.GetFileName(fileNamePath);
                string responseText = "";
                int returnValue = Upload_Request(fileUploadAddress, fileNamePath, saveName, this.progressBarUpload, out responseText);
                if (returnValue == 1)
                {
                    fileUploadCount++;
                    this.listLogMsg.Items.Add(saveName + " " + "上传成功！");
                    Application.DoEvents();
                }
                else
                {
                    this.listLogMsg.Items.Add(saveName + " " + "上传失败！(" + responseText + ")");
                    Application.DoEvents();
                }
            }
        }

        private void btnRetry_Click(object sender, EventArgs e)
        {

        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            FormSettings settings = new FormSettings();
            settings.ShowDialog(this);
        }

        /// <summary>
        /// 将本地文件上传到指定的服务器(HttpWebRequest方法)
        /// </summary>
        /// <param name="address">文件上传到的服务器</param>
        /// <param name="fileNamePath">要上传的本地文件（全路径）</param>
        /// <param name="fileName">文件上传后的名称</param>
        /// <param name="progressBar">上传进度条</param>
        /// <returns>成功返回1，失败返回0</returns>
        private int Upload_Request(string address, string fileNamePath, string fileName, ProgressBar progressBar, out string responseText)
        {
            int returnValue = 0;
            string returnResponseText = "";
            FileStream fs = null;
            BinaryReader r = null;
            try
            {
                progressBar.Maximum = 100;
                progressBar.Minimum = 0;
                progressBar.Value = 0;

                // 要上传的文件 
                fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                r = new BinaryReader(fs);
                long fileLength = fs.Length;

                //时间戳 
                string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");

                //请求头部信息 
                StringBuilder sb = new StringBuilder();
                sb.Append("--");
                sb.Append(strBoundary);
                sb.Append("\r\n");
                sb.Append("Content-Disposition: form-data; name=\"");
                sb.Append("file");
                sb.Append("\"; filename=\"");
                sb.Append(fileName);
                sb.Append("\"");
                sb.Append("\r\n");
                sb.Append("Content-Type: ");
                sb.Append("application/octet-stream");
                sb.Append("\r\n");
                sb.Append("\r\n");
                string strPostHeader = sb.ToString();
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);

                //根据uri创建HttpWebRequest对象 
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
                httpReq.Method = "POST";
                //对发送的数据不使用缓存 
                httpReq.AllowWriteStreamBuffering = false;
                //设置获得响应的超时时间（3000秒） 
                httpReq.Timeout = 3000000;
                httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
                long length = fileLength + postHeaderBytes.Length + boundaryBytes.Length;
                httpReq.ContentLength = length;
                Stream postStream = httpReq.GetRequestStream();

                //每次上传4k 
                int bufferLength = 4096;
                byte[] buffer = new byte[bufferLength];
                //已上传的字节数 
                long offset = 0;
                //开始上传时间 
                DateTime startTime = DateTime.Now;

                int size = r.Read(buffer, 0, bufferLength);
                //发送请求头部消息 
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                while (size > 0)
                {
                    postStream.Write(buffer, 0, size);
                    offset += size;

                    this.lblCurrentUploadFileName.Text = "正在上传：" + fileName;
                    progressBar.Value = (int)(offset * 100.0 / fileLength);
                    TimeSpan span = DateTime.Now - startTime;
                    double second = span.TotalSeconds;
                    this.lblTime.Text = "已用时：" + second.ToString("F2") + "秒";
                    if (second > 0)
                    {
                        lblSpeed.Text = " 速度：" + (offset / 1024.0 / second).ToString("0.00") + "KB/秒";
                    }
                    lblState.Text = "已上传：" + (offset * 100.0 / fileLength).ToString("F2") + "%";
                    lblSize.Text = (offset / 1048576.0).ToString("F2") + "M/" + (fileLength / 1048576.0).ToString("F2") + "M";
                    Application.DoEvents();

                    size = r.Read(buffer, 0, bufferLength);
                }

                //添加尾部的时间戳 
                postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                postStream.Close();

                //获取服务器端的响应 
                WebResponse webRespon = httpReq.GetResponse();
                Stream s = webRespon.GetResponseStream();
                StreamReader sr = new StreamReader(s);
                //读取服务器端返回的消息 
                String sReturnString = sr.ReadToEnd();
                s.Close();
                sr.Close();

                if (sReturnString == "Success")
                {
                    returnValue = 1;
                    this.lblCurrentUploadFileName.Text = "已完成上传：" + fileName;
                    Application.DoEvents();
                }
                else
                {
                    returnValue = 0;
                }
                returnResponseText = sReturnString;

                responseText = returnResponseText;
                return returnValue;
            }
            catch (Exception ex)
            {
                returnValue = 0;
                returnResponseText = ex.Message;
                responseText = returnResponseText;
                return returnValue;
            }
            finally
            {
                try
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    if (r != null)
                    {
                        r.Close();
                    }
                }
                catch (Exception)
                {

                }
            }
        }

        private void btnOpenDirectory_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("explorer.exe", "/select," + templateFilePath);
            }
            catch (Exception)
            {
                this.btnOpenDirectory.Enabled = false;
            }
        }

        private void btnExportErrorToExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = "txt";
            saveFileDialog.Filter = "txt文件 (*.txt)|*.txt";
            saveFileDialog.FileName = "*.txt";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                //if (System.IO.File.Exists(saveFileDialog.FileName))
                //{
                //    if (MessageBox.Show("文件已经存在，是否覆盖？", "文件已存在", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                //    {
                //        return;
                //    }
                //}
                StringBuilder sb = new StringBuilder();
                string errorPattern = @"\A.*上传失败！\(.*\)\z";
                foreach (object error in this.listLogMsg.Items)
                {
                    string errorMsg = error.ToString();
                    if (System.Text.RegularExpressions.Regex.IsMatch(errorMsg, errorPattern))
                    {
                        sb.Append(errorMsg + "\r\n");
                    }
                }
                using (StreamWriter sw = new StreamWriter(saveFileDialog.FileName, false))
                {
                    sw.Write(sb.ToString());
                    sw.Flush();
                    sw.Close();
                }
            }
        }
    }
}
